package com.base.cn.platform.os.service.marketing.shortLink;

import com.base.cn.platform.os.common.md5.MD5;
import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.dao.marketing.shortLink.ShortLinkDao;
import com.base.cn.platform.os.entity.marketing.shortLink.ShortLink;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 短链接加密Biz
 *
 * @author zsw
 * @since 2019-04-22
 */
@Service
public class ShortLinkBiz extends BaseBiz<ShortLink,ShortLinkDao> {

    /**
     * 生成短链接
     *
     * @param longUrl 长链接
     * @return String 短链接
     */
    public String createShortLink(String longUrl) {
        String md5 = MD5.getMD5(longUrl);
        ShortLink shortLink = this.findOne("`urlMD5`='" + md5 + "'",null);
        if (ObjectUtils.isEmpty(shortLink)) {
            shortLink = new ShortLink();
            shortLink.setLongLink(longUrl);
            shortLink.setUrlMD5(md5);
            this.save(shortLink);
            ShortLink _shortLink = this.findOne("`urlMD5`='" + md5 + "'",null);
            _shortLink.setUniqueValue(MD5.getMD5(_shortLink.getId().toString()));
            this.updateById(_shortLink,null);
            return MD5.getMD5(_shortLink.getId().toString());
        }
        return shortLink.getUniqueValue();
    }

    /**
     * 查询短链接
     *
     * @param shortLink
     * @return
     */
    public List<ShortLink> queryShortLink(ShortLink shortLink){
        String uniqueValue = shortLink.getUniqueValue();
        List<ShortLink> shortLinks = this.find(" uniqueValue = '" + uniqueValue + "'", null, null);
        return shortLinks;
    }

}
